---
title: Add foreign key
description: Add a foreign key constraint to a column.
---

## Structure

<YamlJsonTabs>
```yaml
alter_column:
  table: table name
  column: column name
  references:
    name: name of foreign key reference
    table: name of referenced table
    column: name of referenced column
    on_delete: ON DELETE behaviour, can be CASCADE, SET NULL, RESTRICT, or NO ACTION. Default is NO ACTION
  up: SQL expression
  down: SQL expression
```
```json
{
  "alter_column": {
    "table": "table name",
    "column": "column name",
    "references": {
      "name": "name of foreign key reference",
      "table": "name of referenced table",
      "column": "name of referenced column",
      "on_delete": "ON DELETE behaviour, can be CASCADE, SET NULL, RESTRICT, or NO ACTION. Default is NO ACTION"
    },
    "up": "SQL expression",
    "down": "SQL expression"
  }
}
```
</YamlJsonTabs>

## Examples

### Add a foreign key constraint

Add a `FOREIGN KEY` constraint to the `user_id` column in the `posts` table:

<ExampleSnippet example="21_add_foreign_key_constraint.yaml" languange="yaml" />
